package com.atguigu.edu.realtime.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 操作redis的工具类
 */

//旁路缓存：先从缓存中读取数据，如果能够在缓存中读到数据，直接返回（维度命中），否则去HBase中取，取后再放入缓存中
    //redis  k:v
public class RedisUtil {

    private static JedisPool jedisPool;
    static {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setMaxIdle(5);
        jedisPoolConfig.setMaxTotal(100);
        jedisPoolConfig.setBlockWhenExhausted(true);
        jedisPoolConfig.setMaxWaitMillis(5000);
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPool = new JedisPool(jedisPoolConfig,"hadoop104",6379,10000);
    }
    //获取jedis客户端
    public static Jedis getJedis(){
        System.out.println("===获取jedis客户端====");
        Jedis jedis = jedisPool.getResource();
        return jedis;
    }
    //关闭Jedis客户端
    public static void closeJedis(Jedis jedis){
        if (jedis != null){
            System.out.println("===关闭jedis客户端===");
            jedis.close();
        }
    }

    //从Redis读数据
    public static JSONObject readDim(Jedis jedis,String tableName,String id){
        String key=getKey(tableName,id);
        //根据key查数据
        String dimJsonStr = jedis.get(key);
        if (StringUtils.isNotEmpty(dimJsonStr)){
            JSONObject dimJsonObj = JSON.parseObject(dimJsonStr);
            return dimJsonObj;
        }else {
            return null;
        }
    }
    //向redis写数据
    public static void writeDim(Jedis jedis,String tableName,String id,JSONObject dimJsonObj){
        String key = getKey(tableName, id);
        jedis.setex(key,3600*24,dimJsonObj.toJSONString());///往redis写同时设置失效时间
    }


    public static void main(String[] args) {
        Jedis jedis = getJedis();
        System.out.println(jedis.ping());
    }


    public static String getKey(String tableName, String id) {
        return tableName+":"+id;
    }


    //获取异步操作redis连接对象
    public static StatefulRedisConnection<String,String> getRedisAsyncConnection(){
        System.out.println("获取异步获取redis客户端！");
        RedisClient redisClient = RedisClient.create("redis://hadoop102:6379/0");
        StatefulRedisConnection<String, String> redisAsyncConnection = redisClient.connect();
        return redisAsyncConnection;
    }

    //关闭redis连接对象
    public static void closeRedisAsyncConnection(StatefulRedisConnection<String, String> redisAsyncConn) {
        System.out.println("关闭异步获取redis客户端！");
        if (redisAsyncConn != null) {
            redisAsyncConn.close();
        }
    }

    //异步读
    public static JSONObject readDimAsync(StatefulRedisConnection<String,String> redisAsyncConn,String tableName,String id) {
        String key = getKey(tableName, id);
        RedisAsyncCommands<String, String> asyncCommands = redisAsyncConn.async();
        try {
            String dimJsonStr = asyncCommands.get(key).get();
            if (StringUtils.isNotEmpty(dimJsonStr)){
                JSONObject dimJ = JSON.parseObject(dimJsonStr);
                return dimJ;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }


    //异步write
    public static void writeDimAsync(StatefulRedisConnection<String,String> redisAsyncConn,String tableName,String id,JSONObject dimJson) {
        String key = getKey(tableName, id);
        RedisAsyncCommands<String, String> async = redisAsyncConn.async();
        async.setex(key,3600*24,dimJson.toJSONString());
    }
}